﻿using Hangfire;
using Hangfire.Console;
using Hangfire.Server;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HangfireLearn.Task
{
    public class HangfireTask
    {
        public const string DefaultRecurringQueueName = "recurring";

        IConfiguration configuration;

        public HangfireTask(IConfiguration configuration)
        {
            this.configuration = configuration;
        }

        /// <summary>
        /// 立即执行的后台任务，只执行一次
        /// </summary>
        public void StartSimpleJob(int count)
        {
            for (var i =1;i<=count;i++)
            {
                //立即执行的后台任务，只执行一次
                //方式1，执行当前类的方法
                //BackgroundJob.Enqueue(() => DoSimpleJob(null));

                //int id = 100;
                //方式2，执行其它类的方法
                BackgroundJob.Enqueue<Jobs>((jobs) => jobs.DoSimpleJob(i, null, JobCancellationToken.Null));
            }
        }

        /// <summary>
        /// 延时任务，只执行一次
        /// </summary>
        public void StartDelayJob(int count)
        {
            for (var i = 1; i <= count; i++)
            { 
                //延时任务，只执行一次
                //方式1，执行当前类的方法
                //BackgroundJob.Schedule(() => DoDelayJob(null), TimeSpan.FromSeconds(2));

                //方式2，执行其它类的方法
                BackgroundJob.Schedule<Jobs>((jobs) => jobs.DoDelayJob(i, null, JobCancellationToken.Null), TimeSpan.FromSeconds(2));
            }
        }

        /// <summary>
        /// 定时（循环）任务代表可以重复性执行多次
        /// </summary>
        public void StartRecurringJob()
        {
            //定时（循环）任务代表可以重复性执行多次,这里是每分钟执行一次
            //方式1，执行当前类的方法
            //RecurringJob.AddOrUpdate(() => DoRecurringJob(null), Cron.Minutely);


            //方式2，执行其它类的方法
            RecurringJob.AddOrUpdate<Jobs>((jobs) => jobs.DoRecurringJob(null, JobCancellationToken.Null), 
                Cron.Minutely,
                queue: DefaultRecurringQueueName);
        }

        /// <summary>
        /// 继续在其父作业完成时执行：
        /// </summary>
        /// <param name="jobId"></param>
        public void ContinueWith(string jobId)
        {
            BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Continuation!"));
        }

        #region Jobs

        /// <summary>
        /// 执行简单任务，任务上下文PerformContext context会自动设置
        /// </summary>
        /// <param name="context"></param>
        public void DoSimpleJob(PerformContext context)
        {
            JobWithConsole(context, "HangfireTask:Fire-and-forget tasks run ...!");
        }

        public void DoDelayJob(PerformContext context)
        {
            JobWithConsole(context, "HangfireTask: Delayed tasks run...!");
        }

        public void DoRecurringJob(PerformContext context)
        {
            JobWithConsole(context, "HangfireTask:Recurring tasks run ...! ");
        }

        /// <summary>
        /// 执行任务，输出到Hangfire Console
        /// </summary>
        /// <param name="context"></param>
        public void JobWithConsole(PerformContext context,string msg)
        {
            //输出日志
            context.WriteLine($"{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")} - {msg}");

            var progressBar = context.WriteProgressBar();

            //进度条
            // create progress bar
            //var progress = context.WriteProgressBar();
            // update value for previously created progress bar
            //progress.SetValue(100);

            //或
            foreach (var i in Enumerable.Range(1, 50).ToList().WithProgress(progressBar))
            {
                System.Threading.Thread.Sleep(500);
            }
        }

        #endregion
    }


}
